package cn.qfei.qiyuesuo.service.impl;

import cn.qfei.qiyuesuo.service.AuthService;
import cn.qfei.qiyuesuo.vo.TenantAccessTokenVO;
import com.lark.oapi.Client;
import com.lark.oapi.core.enums.AppType;
import com.lark.oapi.core.request.SelfBuiltTenantAccessTokenReq;
import com.lark.oapi.core.response.TenantAccessTokenResp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
@Slf4j
@Service
public class FeishuAuthServiceImp implements AuthService {
    private TenantAccessTokenVO accessToken(String appId, String appSecret) {
        try {
            return getTenantAccessTokenBySelfBuiltApp(appId, appSecret);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static TenantAccessTokenVO getTenantAccessTokenBySelfBuiltApp(String appId, String appSecret) throws Exception {
        // 构建client
        Client client = Client.newBuilder(appId, appSecret)
                .appType(AppType.SELF_BUILT) // 设置app类型，默认为自建
                .logReqAtDebug(true)
                .build();

        // 发起请求
        TenantAccessTokenResp resp = client.ext().getTenantAccessTokenBySelfBuiltApp(
                SelfBuiltTenantAccessTokenReq.newBuilder()
                        .appSecret(appSecret)
                        .appId(appId)
                        .build());
        int code = resp.getCode();
        if (0 != code){
            log.error("获取租户token失败,message={}", resp.getMsg());
            log.error("获取租户token失败,error={}", resp.getError().toString());
            return null;
        }
        TenantAccessTokenVO vo = new TenantAccessTokenVO();
        String tenantAccessToken = resp.getTenantAccessToken();
        int expire = resp.getExpire();
        vo.setTenantAccessToken(tenantAccessToken);
        vo.setExpire(expire);
        return vo;
    }

    @Override
    public String tenantAccessToken( String appId, String appSecret, String appKey) {
        String tokenStr=null;
//        String string = RedisUtil.getString(TENANT_ACCESS_TOKEN_PREFIX + tenantId);
//        if (StringUtils.isEmpty(string)) {
            TenantAccessTokenVO vo = accessToken(appId, appSecret);
            if (vo != null) {

                Duration duration = Duration.ofSeconds(vo.getExpire());
//                RedisUtil.setString(TENANT_ACCESS_TOKEN_PREFIX + tenantId, vo.getTenantAccessToken(), duration);
                tokenStr = vo.getTenantAccessToken();
            }
//        }
        return tokenStr;
    }
}
